import urllib
from google.appengine.api import urlfetch
from google.appengine.api import images
from models.model import *
from updateInfo import getSID

def headlineForStock(setext):
            """ Retrieve headline from Google Insights """
            try:
                url ="http://news.google.com/news?pz=1&cf=all&ned=us&hl=en&q=%s&cf=all&output=rss" % (urllib.quote(setext))
            except:
                # Return -1, meaning wrong stock charcters
                return -1, -1
            
            result = urlfetch.fetch(url=url)
        
            # init headline
            HeadlineTitle=""
            HeadlineURL=""
            # Check if page downloaded
            if result.status_code==200:
                start=result.content.find("<item><title>")
                end=result.content.find("</title>", start)
                HeadlineTitle=result.content[start+13:end]
                start=result.content.find("cluster=")
                end=result.content.find("</guid>", start)
                HeadlineURL=result.content[start+8:end]
                return HeadlineTitle, HeadlineURL
            else:
                return -1,-1
            
def imageForStock(stockEntity):
    """ Retrieve image from Google Images """
    try:
        url = "http://images.google.co.il/images?um=1&hl=iw&tbs=isch:1&sa=1&q=%s&aq=f&aqi=g8&aql=&oq=&gs_rfai=&start=0" % (urllib.quote(stockEntity.stockname))
    
        result = urlfetch.fetch(url=url)
    
        # Check if page downloaded
        if result.status_code==200:
            # Icon size
            iconSize=75
            second = result.content.find(".jpg")
            first = result.content.find("=http:",second-200)
            ImageUrl = result.content[first+1:second+4]

            # Get image, and resize using PIL
            icon=db.Blob(urlfetch.Fetch(ImageUrl).content)
            icon = images.resize(icon , iconSize, iconSize)
            
            stockEntity.stockIcon = icon
            stockEntity.put()
           
            return 1
        else:
            return -1
    except:
        # Return -1, meaning wrong stock charcters
        return -1
    
def downloadYahooData(setext):
    """ Retrieve news headlines from Yahoo """
    try:
        url="http://search.yahooapis.com/NewsSearchService/V1/newsSearch?appid=TJsmpSLV34HpBU6bhtnxc.mIPXOuqGIJpnP2shdzfuWY2eGvklktPBRo17TMFPpfsQo-&query=%s&results=1" % urllib.quote(setext)
        result = urlfetch.fetch(url=url, headers={'Cookie': getSID()})
    except:
        return -1
    
    if result.status_code==200:
        start=result.content.find("totalResultsAvailable")
        end=result.content.find("totalResultsReturned",start)
        try:
            retValue=int(result.content[start+23:end-2])
        except:
            return -1
        return retValue
    else:
        return -1